package com.formiaomiao.demain.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.formiaomiao.demain.R;
import com.formiaomiao.demain.base.BaseActivity;
import com.formiaomiao.demain.base.BaseUrl;
import com.formiaomiao.demain.base.HomeFragmentAdapter;
import com.formiaomiao.demain.fragment.DemainFragment;
import com.formiaomiao.demain.fragment.ImFragment;
import com.formiaomiao.demain.model.PushBean;
import com.formiaomiao.demain.model.TabEntity;
import com.formiaomiao.demain.model.UserBean;
import com.formiaomiao.demain.model.VersionBean;
import com.formiaomiao.demain.model.WeatherBean;
import com.formiaomiao.demain.service.LocationService;
import com.formiaomiao.demain.service.PushIntentService;
import com.formiaomiao.demain.util.GetAppVersion;
import com.formiaomiao.demain.util.MessageEvent;
import com.formiaomiao.demain.util.PreferenceUtils;
import com.formiaomiao.demain.util.PreferenceValues;
import com.formiaomiao.demain.util.SetLeftBgUtils;
import com.formiaomiao.demain.util.StaticValues;
import com.formiaomiao.demain.util.ToastUtils;
import com.formiaomiao.demain.util.UUIDS;
import com.formiaomiao.demain.util.UseGlideUtils;
import com.formiaomiao.demain.weight.LoadingDialog;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMContactListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.util.NetUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.mob.pushsdk.MobPush;
import com.mob.pushsdk.MobPushCustomMessage;
import com.mob.pushsdk.MobPushNotifyMessage;
import com.mob.pushsdk.MobPushReceiver;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;
import skin.support.flycotablayout.widget.SkinSlidingTabLayout;

public class MainActivity extends BaseActivity implements MobPushReceiver {

    private static final String TAG = "MainActivity";
    @BindView(R.id.iv_main_open)
    ImageView ivMainOpen;
    @BindView(R.id.tv_appname)
    TextView tvAppname;
    @BindView(R.id.iv_main_code)
    ImageView ivMainCode;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.tab)
    CommonTabLayout tab;
    @BindView(R.id.v_msg_count)
    View vMsgCount;
    @BindView(R.id.main_content_frame_parent)
    RelativeLayout mainContentFrameParent;
    @BindView(R.id.ll_left)
    ImageView llLeft;
    @BindView(R.id.v_bg)
    View vBg;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_dayweather)
    TextView tvDayweather;
    @BindView(R.id.tv_friend)
    TextView tvFriend;
    @BindView(R.id.tv_follow)
    TextView tvFollow;
    @BindView(R.id.tv_weather)
    TextView tvWeather;
    @BindView(R.id.tv_setting)
    TextView tvSetting;
    @BindView(R.id.main_left_drawer_layout)
    RelativeLayout mainLeftDrawerLayout;
    @BindView(R.id.main_drawer_layout)
    DrawerLayout mainDrawerLayout;
    @BindView(R.id.tv_day)
    TextView tvDay;
    @BindView(R.id.tv_c)
    TextView tvC;
    // 抽屉菜单对象
    private ActionBarDrawerToggle drawerbar;

    WeatherBean weatherBean = new WeatherBean();

    MobPush mobPush = new MobPush();

    Socket mSocket;

    public static MainActivity main;

    //底部导航栏的文字和图片
    private String[] mTitles = {"广场", "消息"};
    private int[] unImages = {R.mipmap.quanunselect, R.mipmap.newsunselect};
    private int[] Images = {R.mipmap.quanselect, R.mipmap.newsselect};
    ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    LoadingDialog loadingDialog;
    AlertDialog Dialog;
    AlertDialog.Builder dialog;

    UserBean userBean = new UserBean();
    private ImageView ivFriendHead;
    private TextView tvFriendName;
    private TextView tvFriendReason;

    private Badge badge;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        main = this;
        EventBus.getDefault().register(this);
        startService(new Intent(this, LocationService.class));
        DataInit();
        initLayout();
        initEvent();
    }

    public void initLayout() {
        GetVersion();
        mobPush.addPushReceiver(this);
        loadingDialog = new LoadingDialog(this);
        //设置菜单内容之外其他区域的背景色
        mainDrawerLayout.setScrimColor(Color.TRANSPARENT);
        tvAppname.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/EuroseWideHeavy Regular.TTF"));
        tvC.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/HYT.ttf"));
        tvDay.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/HYT.ttf"));
        tvDayweather.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/HYT.ttf"));
//        SetLeftBgUtils.setLeft(this, llLeft, vBg);
        tvName.setText(StaticValues.nickname);
        if (StaticValues.userhead.equals("")) {
            Glide.with(this).load(R.mipmap.ic_launcher).into(ivHead);
        } else {
            UseGlideUtils.setGlide(this, StaticValues.userhead, ivHead);
        }
        DemainSocket();
    }

    public void DataInit() {
        //注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(new MyConnectionListener());
        EMClient.getInstance().contactManager().setContactListener(new MyContactListener());
        HomeFragmentAdapter adapter = new HomeFragmentAdapter(getSupportFragmentManager());
        //设置tab的文字
        ArrayList<String> titles = new ArrayList<>();
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], Images[i], unImages[i]));
        }
        adapter.setTitles(titles);
        //设置tab对应得fragment

        badge = new QBadgeView(this).bindTarget(vMsgCount);
        badge.setBadgeGravity(Gravity.END | Gravity.TOP);
        badge.setBadgeTextSize(14, true);
        badge.setBadgePadding(6, true);
        badge.setGravityOffset(2.0f, true);
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(DemainFragment.newInstance());
        fragments.add(ImFragment.newInstance());
        adapter.setFragments(fragments);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(2);
        //设置默认第一个为选中的tab
        tab.getChildAt(0).isSelected();
        tab.setTabData(mTabEntities);
        tab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                tab.setCurrentTab(i);
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
        badge.setOnDragStateChangedListener(new Badge.OnDragStateChangedListener() {
            @Override
            public void onDragStateChanged(int dragState, Badge badge, View targetView) {
                if (!ImFragment.isshow) {
                    viewPager.setCurrentItem(1);
                    return;
                } else {
                    if (dragState == STATE_SUCCEED) {
                        EventBus.getDefault().post(new MessageEvent("清空未读消息"));
                    }
                }
            }
        });
        mainDrawerLayout.addDrawerListener(mSimpleDrawerListener);
    }

    private void FriendApplyDialog(final UserBean userBean, String s) {
        View v = LayoutInflater.from(this).inflate(R.layout.dialog_friend_apply, null);
        initsView(v, userBean, s);
        dialog = new AlertDialog.Builder(this);
        dialog.setView(v);
        dialog.setNegativeButton("同意", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            EMClient.getInstance().contactManager().acceptInvitation(userBean.getData().getUserName());
                            Looper.prepare();
                            AddFriendInit(userBean.getData().getNeteaseUid());
                            Looper.loop();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
        dialog.setPositiveButton("拒绝", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            EMClient.getInstance().contactManager().declineInvitation(userBean.getData().getUserName());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
        Dialog = dialog.create();
        Dialog.setCancelable(false);
        Dialog.show();
    }

    /**
     * 好友申请dialog
     */
    private void FriendApply(final boolean apply, String username, final String s) {
        OkGo.<String>post(BaseUrl.USERNAMESELECT)
                .headers("Authorization", PreferenceUtils.getString(this, PreferenceValues.TOKEN))
                .params("username", username)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.body().contains("200")) {
                            userBean = gson.fromJson(response.body(), UserBean.class);
                            if (apply) {
                                FriendApplyDialog(userBean, s);
                            } else {
                                ToastUtils.show(MainActivity.this,
                                        userBean.getData().getNickName() + "拒绝了您的好友申请");
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });
    }

    //设置开关监听
    private void initEvent() {
        drawerbar = new ActionBarDrawerToggle(this, mainDrawerLayout, R.mipmap.ic_launcher, R.string.open, R.string.close) {
            //菜单打开
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            // 菜单关闭
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };

        mainDrawerLayout.setDrawerListener(drawerbar);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mainDrawerLayout.removeDrawerListener(mSimpleDrawerListener);
        EventBus.getDefault().unregister(this);
        deleteFile(new File(Environment.getExternalStorageDirectory() + "/demain/img/corp"));
        stopService(new Intent(MainActivity.this, LocationService.class));
        mSocket.close();
    }

    @Override
    public void finish() {
        super.finish();
        MobPush.removePushReceiver(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent msg) {
        if (msg.getMessage().equals("定位成功")) {
            WeatherDataInit();
        } else if (msg.getMessage().equals("更改头像")) {
            UseGlideUtils.setGlide(this, StaticValues.userheads, ivHead);
        } else if (msg.getMessage().equals("更改昵称")) {
            tvName.setText(StaticValues.nickname);
        } else if (msg.getMessage().equals("更改密码")) {
            PreferenceUtils.setString(MainActivity.this, PreferenceValues.PASSWORD, "");
            PreferenceUtils.setString(MainActivity.this, PreferenceValues.USERNAME, "");
            startActivity(new Intent(MainActivity.this, LoginActivity.class));
            finish();
        } else if (msg.getMessage().equals("侧滑栏背景")) {
            SetLeftBgUtils.setLeft(this, llLeft, vBg);
        } else if (msg.getMessage().equals("点击聊天推送")) {
            if (mainDrawerLayout.isDrawerOpen(mainLeftDrawerLayout)) {
                mainDrawerLayout.closeDrawer(mainLeftDrawerLayout);
            }
        } else if (msg.getMessage().contains("未读")) {
            badge.setBadgeNumber(Integer.parseInt(msg.getMessage().split(":")[1]));
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Uri uri = intent.getData();
        if (!uri.getScheme().equals("wechat")) {
            return;
        }
        if (uri.getPath().contains("/conversation")) {
            EventBus.getDefault().post(new MessageEvent("点击聊天推送"));
            viewPager.setCurrentItem(1);
        }
    }

    //flie：要删除的文件夹的所在位置
    private void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }

    // 保存点击的时间
    private long exitTime = 0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick({R.id.iv_main_open, R.id.iv_main_code, R.id.iv_head, R.id.tv_weather
            , R.id.tv_setting, R.id.tv_friend, R.id.tv_follow, R.id.main_content_frame_parent})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_main_open:
                if (mainDrawerLayout.isDrawerOpen(mainLeftDrawerLayout)) {
                    mainDrawerLayout.closeDrawer(mainLeftDrawerLayout);
                } else {
                    mainDrawerLayout.openDrawer(mainLeftDrawerLayout);
                }
                break;
            case R.id.iv_main_code:
                ToastUtils.show(this, "暂未开通");
                break;
            case R.id.iv_head:
                startActivity(new Intent(this, UpdateUserActivity.class));
                break;
            case R.id.tv_weather:
                startActivity(new Intent(this, WeatherActivity.class));
                break;
            case R.id.tv_setting:
                startActivity(new Intent(this, SettingsActivity.class));
                break;
            case R.id.tv_friend:
                startActivity(new Intent(this, FriendActivity.class));
                break;
            case R.id.tv_follow:
                startActivity(new Intent(this, FollowActivity.class));
                break;
            case R.id.main_content_frame_parent:
                Log.e(TAG, "");
                break;
        }
    }

    private void initsView(View v, final UserBean userBean, String s) {
        ivFriendHead = (ImageView) v.findViewById(R.id.iv_friend_head);
        tvFriendName = (TextView) v.findViewById(R.id.tv_friend_name);
        tvFriendReason = (TextView) v.findViewById(R.id.tv_friend_reason);
        try {
            if (userBean.getData().getUserHead() == null) {
                Glide.with(this).load(R.mipmap.ic_launcher).into(ivFriendHead);
            } else {
                UseGlideUtils.setGlide(this, userBean.getData().getUserHead(), ivFriendHead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        tvFriendName.setText(userBean.getData().getNickName());
        tvFriendReason.setText(s);
        ivFriendHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, DemainUserActivity.class);
                intent.putExtra("id", userBean.getData().getId());
                intent.putExtra("name", userBean.getData().getNickName());
                intent.putExtra("head", userBean.getData().getUserHead());
                intent.putExtra("username", userBean.getData().getUserName());
                startActivity(intent);
            }
        });
    }

    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
                    } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        dialog = new AlertDialog.Builder(MainActivity.this);
                        dialog.setTitle("您的账号已在其他的地方登陆，如果不是您本人操作，请联系管理员修改密码");
                        dialog.setNegativeButton("退出", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        });
                        dialog.setPositiveButton("重新登录", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                PreferenceUtils.setString(MainActivity.this, PreferenceValues.PASSWORD, "");
                                PreferenceUtils.setString(MainActivity.this, PreferenceValues.USERNAME, "");
                                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                                finish();
                            }
                        });
                        Dialog = dialog.create();
                        Dialog.setCancelable(false);
                        Dialog.show();
                    } else {
                        if (NetUtils.hasNetwork(MainActivity.this)) {
                            System.out.println("连接不到聊天服务器");
                        } else {
                            System.out.println("当前网络不可用，请检查网络设置");
                        }
                    }
                }
            });
        }
    }

    @Override
    public void onCustomMessageReceive(Context context, MobPushCustomMessage mobPushCustomMessage) {
        //接收自定义消息
        System.out.println(mobPushCustomMessage);
    }

    @Override
    public void onNotifyMessageReceive(Context context, MobPushNotifyMessage mobPushNotifyMessage) {
        //接收通知消息
        System.out.println(mobPushNotifyMessage);
    }

    @Override
    public void onNotifyMessageOpenedReceive(Context context, MobPushNotifyMessage mobPushNotifyMessage) {
        //接收通知消息被点击事件
        try {
            if (mobPushNotifyMessage.getExtrasMap().get("key").equals("1")) {
                String url = "weixin://";
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTagsCallback(Context context, String[] strings, int i, int i1) {
        //接收tags的增改删查操作
    }

    @Override
    public void onAliasCallback(Context context, String s, int i, int i1) {
        //接收alias的增改删查操作
    }

    private DrawerLayout.SimpleDrawerListener mSimpleDrawerListener = new DrawerLayout.SimpleDrawerListener() {
        @Override
        public void onDrawerOpened(View drawerView) {
            //档DrawerLayout打开时，让整体DrawerLayout布局可以响应点击事件
            drawerView.setClickable(true);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }
    };

    /**
     * 获取天气信息
     */
    public void WeatherDataInit() {
        HttpParams params = new HttpParams();
        params.put("key", "246634d11162f");
        params.put("city", LocationService.city);
        params.put("province", LocationService.province);
        OkGo.<String>post("http://apicloud.mob.com/v1/weather/query").tag(this).params(params).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                weatherBean = gson.fromJson(response.body(), WeatherBean.class);
                tvDayweather.setText(weatherBean.getResult().get(0).getTemperature().split("℃")[0]);
                tvDay.setText(weatherBean.getResult().get(0).getWeather());
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }
        });
    }

    /**
     * 加为好友
     */
    private void AddFriendInit(String neteaseUid) {
        HttpParams params = new HttpParams();
        params.put("friendfrom", StaticValues.userid);
        params.put("neteaseUid", neteaseUid);
        OkGo.<String>post(BaseUrl.ADDFRIEND)
                .headers("Authorization", PreferenceUtils.getString(this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {

                if (response.body().contains("成功")) {
                    ToastUtils.show(MainActivity.this, "添加成功");
                    EventBus.getDefault().post(new MessageEvent("添加好友"));
                } else {
                    ToastUtils.show(MainActivity.this, "添加失败");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
            }
        });

    }

    public void DemainSocket() {
        try {
            mSocket = IO.socket("http://39.105.26.114:9092?mac=" + UUIDS.getUUID());
//            mSocket = IO.socket("http://192.168.137.1:9092?mac=" + UUIDS.getUUID());
            mSocket.connect();
            mSocket.emit("messageevent", "a");
            mSocket.on("messageevent", new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    System.out.println(args[0].toString());
                    if (args[0].toString().equals("a")) {
                        new Timer().schedule(new TimerTask() {
                            @Override
                            public void run() {
                                mSocket.emit("messageevent", "a");
                            }
                        }, 30000);
                    } else {
                        PushBean bean = new PushBean();
                        bean = gson.fromJson(args[0].toString(), PushBean.class);
                        startService(new Intent(MainActivity.this,
                                PushIntentService.class).putExtra("data", bean.getData())
                                .putExtra("name", getResources().getString(R.string.app_name)));
                    }
                }
            });
        } catch (URISyntaxException e) {
            e.printStackTrace();
            DemainSocket();
        }
    }

    private void GetVersion(){
        OkGo.<String>post(BaseUrl.SELECTCODE)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        VersionBean versionBean = new VersionBean();
                        if(response.body().contains("200")){
                            versionBean = gson.fromJson(response.body(),VersionBean.class);
                            UpdataInit(versionBean.getData().getVersionCode(),
                                    versionBean.getData().getUpdateContent(),
                                    versionBean.getData().getApkurl());
                        }
                    }
                });
    }

    /**
     * 更新操作
     *
     * @param version
     * @param updatamsg
     */
    public void UpdataInit(int version, String updatamsg, final String url) {
        if (version > Integer.parseInt(GetAppVersion.getVersionCode(MainActivity.this))) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
            dialog.setTitle("发现新版本是否更新？");
            dialog.setMessage(updatamsg);
            dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialog.setPositiveButton("更新", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                }
            });
            dialog.show();
        }
    }

    public class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(String username) {
            //增加了联系人时回调此方法
        }

        @Override
        public void onContactDeleted(String username) {
            //被删除时回调此方法
            EventBus.getDefault().post(new MessageEvent("删除好友"));
        }

        @Override
        public void onContactInvited(String username, String reason) {
            //收到好友邀请
            FriendApply(true, username, reason);
        }

        @Override
        public void onFriendRequestAccepted(String username) {
            //好友请求被同意

        }

        @Override
        public void onFriendRequestDeclined(String username) {
            //好友请求被拒绝
            FriendApply(false, username, "");
        }
    }

}
